Ext.namespace('SLM');

SLM.EventsGrid = function(config) {

	var Collection = Ext.data.Record.create([
			{name: 'event_type'}
		,	{name: 'event_type_id'}
		,	{name: 'event_id'}
		,	{name: 'title'}
		, 	{name: 'date_start'}
		, 	{name: 'date_end'}
		, 	{name: 'land_id'}
		,	{name: 'property'}
	]);
	
	var myReader = new Ext.data.JsonReader({
			totalProperty: "total"
		,	root: "records"
		,	id: "event_id"
	}, Collection );

	this.store = new Ext.data.GroupingStore({
			reader: myReader
		,	url: Config.baseUrl + 'resources/api/app.php'
		,	baseParams: { cmd: 'event-list', start: 0, limit: 100 }
		,	sortInfo:{field: 'event_type', direction: "ASC"}			
		,	groupField: 'event_type'
		,	remoteSort: true		
		,	listeners: {			
				'beforeload': function( store, o ) {
						var filters = Ext.getCmp('event_form').getForm().getValues( true );

						var filter = {
								condition: 'AND'
							,	items: []
						}
						
						var found = false;
						var condition = null;
						Ext.each( filters.split("&"), function( tmpField, index ) {
							tmpField = tmpField.split("=");
							if (tmpField[1] != '') {
								found = true;
								switch( tmpField[0] ) {
									case 'date_start':
										condition = 'GREATER_EQUAL';
										break;
									case 'date_end':
										condition = 'LESS_EQUAL';
										break;
									default:
										condition = 'EQUAL';
										break;
								}
								filter.items.push({
										field: tmpField[0]
									,	condition: condition
									,	value: tmpField[1]
								});
							}
						});
						
						if (!found) {
							filter = null;
						}
						
						var params = {
								userFilter: Ext.getCmp('my_events').pressed
							,	filter: Ext.encode(filter)
						}
						
						Ext.apply(o.params, params );
				}
			}			
	});

  var pagingBar = new Ext.PagingToolbar({
			pageSize: 100
		,	store: this.store
		,	displayInfo: true
		,	displayMsg: 'Displaying events {0} - {1} of {2}'
		,	emptyMsg: "No events to display"
	});

	this.sm =	new Ext.grid.RowSelectionModel({
			singleSelect: true
		,	listeners: {
					rowselect: function(sm, row, rec){
						this.enableDisbleEvent();
					}
				,	rowdeselect: function(sm, row, rec){
						this.enableDisbleEvent();
					}
				,	scope: this	
			}
	});
	
	Ext.apply(this, config, {
			id: 'events'
		,	iconCls: 'icon_events_grid'
		,	title: 'Events'
		, 	loadMask: true
		,	columns: [
					{header: "Event Type", id: 'event_type', width: 110, dataIndex: 'event_type', sortable: true}
				,	{header: "Property", id: 'property', width: 200, dataIndex: 'property', sortable: true}
				,	{header: "Title", width: 165, dataIndex: 'title', sortable: true}
				,	{header: "Event Start", width: 110, dataIndex: 'date_start', sortable: true, align: 'right', renderer: this.renderDate }
				,	{header: "Event End", width: 110, dataIndex: 'date_end', sortable: true, align: 'right', renderer: this.renderDate }
			]
		,	border: false
		,	sm: this.sm
		,	bbar: pagingBar
		,	view: new Ext.grid.GroupingView({
					groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "" : ""]})'
				,	emptyText: 'No events to display.'
			})
		,	listeners: {
					rowdblclick: function(grid, row) {
						var data = this.getSelectionModel().selections.items[0].data;
						var eventViewer = new SLM.EventViewer({}, data);
						eventViewer.show();
					}
				,	rowcontextmenu: this.showContextMenu	
			}
	});

	SLM.EventsGrid.superclass.constructor.apply(this, arguments);

};

Ext.extend( SLM.EventsGrid, Ext.grid.GridPanel, {
		enableDisbleEvent: function(){
			selection = this.getSelectionModel().getSelected();
			var found = false;
			if(Ext.isDefined(selection)){
				var selected = selection.data;
				found = this.checkLandId(selected.land_id);
			}
			if (this.getSelectionModel().getCount() > 0 && found) {
				Ext.getCmp('btn-edit-event').enable();							
				Ext.getCmp('btn-delete-event').enable();							
			} else {
				Ext.getCmp('btn-edit-event').disable();
				Ext.getCmp('btn-delete-event').disable();
			}
		}
	,	showContextMenu: function(grid, row, e){
			grid.getSelectionModel().selectRow(row);
			var record = grid.getSelectionModel().getSelected().data;
			var items = [];
			var found = this.checkLandId(record.land_id);
			if(found){
				items.push({
						text: 'Delete Event'
					,	iconCls: 'icon_events_delete'
					,	scope: this	
					,	handler: function(me) {
							this.removeRequest(record);
						}  
				});
				var menu = new Ext.menu.Menu({
					items: items
				});
				var xy = e.getXY();
				menu.showAt(xy);
			}
		}
	,	removeRequest: function(record){
			var confirmMsg = String.format('Are you sure you would like to remove event "{0}" from property "{1}"', record.title, record.property);
			Ext.Msg.confirm('Confirm', confirmMsg, function(btn){
					if(btn == 'yes'){
						var myMask = new Ext.LoadMask(this.body,{msg: 'Please wait...'});
						myMask.show();
						Ext.Ajax.request({
								url: Config.baseUrl + 'resources/api/app.php'
							,	scope: this
							,	params: { 
										cmd: 'removeEvent'
									,	event_id: record.event_id
								}
							,	success: function(response) {
									var o = Ext.decode(response.responseText);
									if(o.success){
										this.getStore().reload();
									}else {
										Ext.Msg.alert('Error', o.error.msg);
									}
									myMask.hide();	
								}
							,	failure: function(){
									Ext.Msg.alert('Notice', 'Fatal Error.');
									myMask.hide();
								}	
						});
					}
			},this);	
		}
	,	checkLandId: function(landId){
			var allowedLand = Ext.getCmp('events-panel').allowedLand;
			var found = false;
			for(var i=0; i<allowedLand.length; i++){
				if(allowedLand[i] == landId){
					found = true;
					break;
				}
			}
			return found;
		}
	,	renderDate: function( value ) {
			if ( value == '0000-00-00') {
				return('');
			} else {
				dt=new Date(value);
				return ( dt.format('F j, Y') );
			}
		}
		
});

Ext.reg('EventsGrid', SLM.EventsGrid);